#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

//由服务端来创建命名管道，客户端不能创建管道，所以要分身份
#define Creater 1
#define User 2

#define Write O_WRONLY
#define Read O_RDONLY
#define SIZE 1024
class NamedPipe
{
private:
    //以什么方式打开命名管道
    bool OpenNamedPipe(int mode)
    {
        _fd = open(_path.c_str(), mode); 
        if(_fd < 0) return false;
        return true;
    }

public:
    //创建命名管道文件
    NamedPipe(std::string path,int id)
    :_path(path)
    ,_id(id)
    {
        if(_id == Creater)
        {
            int ret = mkfifo(path.c_str(), 0666);
            if(ret !=0)
            {
                perror("mkfifo");    
            } 
        }
    }
   
    bool ReadOpen()
    {
       return OpenNamedPipe(Read);
    }
    bool WriteOpen()
    {
        return OpenNamedPipe(Write);  
    }

    int WriteForPipe(const std::string& message)
    {
        return write(_fd, message.c_str(), message.size());
    }
    int ReadFromPipe(std::string& message)
    {
        char buffer[SIZE];
        int n = read(_fd, buffer, sizeof(buffer));
        if(n>0)
        {
            buffer[n] = 0;
            message = buffer;
        }
        return n;
    } 

    //删除命名管道文件
    ~NamedPipe()
    {
        if(_id == Creater)
        {
            int ret = unlink(_path.c_str());
            if(ret !=0)
            {
                perror("unlink");
            } \
        }
        if(_fd != -1) close(_fd);
    }
private:
std::string _path; 
int _id;
int _fd = -1;
};
